package com.mf.morefun.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;

public class StorageUtil {
    public static boolean writeStorage(){
        try {
            if (!TextUtils.equals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState())) return false;

            File directory = Environment.getExternalStorageDirectory();
            if (!directory.exists()) return false;

            File parent = new File(directory, "Android");
            if (parent.exists() && parent.isFile()) {
                if (!parent.delete()) return false;
            }
            if (!parent.exists()) {
                if (!parent.mkdirs()) return false;
            }
            File file = new File(parent, "ANDROID.PERMISSION.TEST");
            if (file.exists()) {
                return file.delete();
            } else {
                return file.createNewFile();
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public static boolean readStorage(){
        try {
            if (!TextUtils.equals(Environment.MEDIA_MOUNTED, Environment.getExternalStorageState())) return false;

            File directory = Environment.getExternalStorageDirectory();
            if (!directory.exists()) return true;

            long modified = directory.lastModified();
            String[] pathList = directory.list();
            return modified > 0 && pathList != null;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public static boolean camearaUtil(Context mContext){
        Camera camera = null;
        try {
            camera = Camera.open();
            Camera.Parameters parameters = camera.getParameters();
            camera.setParameters(parameters);
            camera.setPreviewCallback(PREVIEW_CALLBACK);
            camera.startPreview();
            return true;
        } catch (Throwable e) {
            PackageManager packageManager = mContext.getPackageManager();
            return !packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA);
        } finally {
            if (camera != null) {
                camera.stopPreview();
                camera.setPreviewCallback(null);
                camera.release();
            }
        }
    }

    private static final Camera.PreviewCallback PREVIEW_CALLBACK = new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
        }
    };
}
